<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <div id="app">
    <div>
      <span>姓名:</span>
      <input type="text" v-model="username" />
    </div>
    <div>
      <span>年龄:</span>
      <input type="number" v-model.number="age" />
    </div>
    <div>
      <span>性别:</span>
      <select v-model="selectedGender">
        <option value="男" name="gender">男</option>
        <option value="女" name="gender">女</option>
      </select>
    </div>
    <div>
      <button @click="addOrUpdate">添加/修改</button>
    </div>
    <div>
      <table border="1" cellpadding="10" cellspacing="0" v-if="list.length">
        <tr>
          <th>序号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
        <tr v-for="(item, index) in list" :key="item.id">
          <td>{{ index + 1 }}</td>
          <td>{{ item.name }}</td>
          <td>{{ item.age }}</td>
          <td>{{ item.sex }}</td>
          <td>
            <button @click="put(item)">编辑</button>
            <button @click="del(item)">删除</button>
          </td>
        </tr>
      </table>
    </div>
  </div>
  <script src="../js/vue.js"></script>
  <script>
    const app = new Vue({
      el: '#app',
      data: {
        list: [
          { id: 1, name: 'Tom', age: 18, sex: '男' },
          { id: 2, name: 'Jerry', age: 20, sex: '女' },
        ],
        username: '',
        age: '',
        selectedGender: '',
        editingItem: null
      },
      methods: {
        del(item) {
          // 从列表中删除指定的项
          const index = this.list.indexOf(item);
          if (index > -1) {
            this.list.splice(index, 1);
          }
        },
        put(item) {
          // 进入编辑模式，将当前项的信息填充到输入框和选择框中
          this.editingItem = item;
          this.username = item.name;
          this.age = item.age;
          this.selectedGender = item.sex;
        },
        addOrUpdate() {
          if (this.editingItem) {
            // 修改
            this.editingItem.name = this.username;
            this.editingItem.age = this.age;
            this.editingItem.sex = this.selectedGender;
            this.editingItem = null; // 完成修改，退出编辑模式
          } else {
            // 添加
            const newItem = {
              id: this.list.length > 0? this.list[this.list.length - 1].id + 1 : 1,
              name: this.username,
              age: this.age,
              sex: this.selectedGender
            };
            this.list.push(newItem);
          }
          // 清空输入框和选择框
          this.username = '';
          this.age = '';
          this.selectedGender = '';
        }
      }
    });
  </script>
</body>

</html>